﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace Sushi.Sample.Client.Simulator
{
	/// <summary>
	/// Provides a custom behavior that allows a client to capture messages and log
	/// them or assist in debugging messages.
	/// </summary>
	public class MessageViewerInspector : IEndpointBehavior, IClientMessageInspector
	{
		///<summary>
		/// Property used to store the request message.
		///</summary>
		public string RequestMessage { get; set; }

		///<summary>
		/// Property used to store the response message.
		///</summary>
		public string ResponseMessage { get; set; }

		///<summary>
		/// Unused in our implementation.
		///</summary>
		public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
		{
		}

		///<summary>
		/// Adds our inspector to the runtime
		///</summary>
		public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
		{
			clientRuntime.MessageInspectors.Add(this);
		}

		///<summary>
		/// Unused in our implementation.
		///</summary>
		public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
		{
		}

		///<summary>
		/// Unused in our implementation.
		///</summary>
		public void Validate(ServiceEndpoint endpoint)
		{
		}

		///<summary>
		/// Unused in our implementation.
		///</summary>
		public object BeforeSendRequest(ref Message request, IClientChannel channel)
		{
			return null;
		}

		///<summary>
		/// Captures the response message.
		///</summary>
		void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState)
		{
			ResponseMessage = reply.ToString();
		}

		///<summary>
		/// Captures the request message.
		///</summary>
		object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
		{
			RequestMessage = request.ToString();
			return null;
		}
	}
}
